package com.fafi.selfmvc.controller;

import com.fafi.selfmvc.vo.MyBean;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController //等同@Controller+@ResponsrBody
@RequestMapping("user")
public class UserController {

	@GetMapping
	public ModelAndView list(Model model) {
		System.out.println(model.getAttribute("name"));
		model.addAttribute("title","userlist");
		return new ModelAndView("user/list","userModel",model);
	}

	/**
	 * http://localhost:8080/example/user/45
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping("{id}")
	public ModelAndView byid(@PathVariable("id") int id, Model model) {
		model.addAttribute("title","byid"+id);
		return new ModelAndView("user/list","userModel",model);
	}

	@GetMapping("/form")
	public ModelAndView from(Model model) {
		model.addAttribute("title","createform");
		model.addAttribute("user",new MyBean(4,"tom"));
		return new ModelAndView("user/list","userModel",model);
	}

	/**
	 * 保存 从user/form insert
	 * @param user
	 * @param model
	 * @return
	 */
	@PostMapping("insert")
	public ModelAndView insert(MyBean user, Model model) {
		System.out.println(user.getName()+"--"+user.getAge());
		model.addAttribute("operate","insertUser");
		model.addAttribute("user",new MyBean(4,"tom"));
		return new ModelAndView("redirect:/user");
	}

	/**
	 * 更新 从user/form update
	 * @param user
	 * @param model
	 * @return
	 */
	@PutMapping("update")
	public ModelAndView update(MyBean user, Model model) {
		System.out.println(user.getName()+"--put--"+user.getAge());
		model.addAttribute("operate","updateUser");
		model.addAttribute("user",new MyBean(4,"tom"));
		return new ModelAndView("redirect:/user");
	}

	@GetMapping(value="update/{id}")
	public ModelAndView update(@PathVariable("id") int id, Model model) {
		System.out.println("id:"+id);
		model.addAttribute("operate","updateUserbyid");
		model.addAttribute("user",new MyBean(4,"tom"));
		return new ModelAndView("user/list","userModel",model);
	}

	/**
	 * 删除
	 * @param id
	 * @param model
	 * @return
	 */
	@DeleteMapping(value="delete/{id}")
	public ModelAndView delete(@PathVariable("id") int id, Model model) {
		System.out.println("deleteid:"+id);
		model.addAttribute("operate","deleteUser");
		model.addAttribute("user",new MyBean(4,"tom"));
		return new ModelAndView("redirect:/user");
	}
}
